package com.gqr.future;


import java.util.concurrent.*;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:FutureTaskDemo
 * author:guqingrong
 * Date:2024-05-20 21:14
 * Description:演示FutureTask的用法
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class FutureTaskDemo {
    public static void main(String[] args) {
        Task task = new Task();
        FutureTask<Integer> integerFutureTask = new FutureTask<>(task);

        // 在线程中运行
//        new Thread(integerFutureTask).start();
        // 线程池中运行
        ExecutorService service = Executors.newCachedThreadPool();
        service.submit(integerFutureTask);

        try {
            System.out.println("task运行结果"+integerFutureTask.get());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }


}
class Task implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        System.out.println("子线程正在计算");
        Thread.sleep(3000);
        int sum =0;
        for (int i = 0; i < 100; i++) {
            sum+=i;
        }
        return sum;
    }
}
